'use client'

import React from 'react'
import { Button, Result } from 'antd'

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props)
        this.state = { hasError: false, error: null, errorInfo: null }
    }

    static getDerivedStateFromError(error) {
        // 更新 state 使下一次渲染能够显示降级后的 UI
        return { hasError: true }
    }

    componentDidCatch(error, errorInfo) {
        // 你同样可以将错误日志上报给服务器
        if (process.env.NODE_ENV === 'development') {
            console.error('ErrorBoundary caught an error:', error, errorInfo)
        }
        this.setState({
            error: error,
            errorInfo: errorInfo
        })
    }

    render() {
        if (this.state.hasError) {
            return (
                <div className="min-h-screen flex items-center justify-center bg-gray-50">
                    <Result
                        status="error"
                        title="页面出现错误"
                        subTitle="抱歉，页面遇到了一些问题。请刷新页面重试，或联系技术支持。"
                        extra={[
                            <Button
                                type="primary"
                                key="refresh"
                                onClick={() => window.location.reload()}
                            >
                                刷新页面
                            </Button>,
                            <Button
                                key="home"
                                onClick={() => window.location.href = '/'}
                            >
                                返回首页
                            </Button>
                        ]}
                    />
                    {process.env.NODE_ENV === 'development' && (
                        <details className="mt-8 p-4 bg-red-50 border border-red-200 rounded">
                            <summary className="cursor-pointer text-red-700 font-medium">
                                错误详情 (开发模式)
                            </summary>
                            <div className="mt-2 text-sm text-red-600">
                                <p><strong>错误:</strong> {this.state.error && this.state.error.toString()}</p>
                                <pre className="mt-2 whitespace-pre-wrap">
                                    {this.state.errorInfo.componentStack}
                                </pre>
                            </div>
                        </details>
                    )}
                </div>
            )
        }

        return this.props.children
    }
}

export default ErrorBoundary